import { message } from 'antd'
import axios from 'axios'
import { getToken, removeToken } from 'utils/storage'
import history from './history'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/', // 请求的基准地址
  timeout: 5000, // 超时时间
})

// 请求拦截器
instance.interceptors.request.use(
  function(config) {
    const token = getToken()
    if (token) {
      config.headers.Authorization = 'Bearer ' + token.token
    }
    // 请求配置的统一处理
    return config
  },
  function (error) {
    // 请求出错
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 响应成功
    return response.data
  },
  function (error) {
    // 响应失败
    if (error.response?.status === 401) {
      removeToken()
      history.push('/login')
      message.error('登录过期，请重新登录！')
    }
    return Promise.reject(error)
  }
)

export const createAPI = (url, method, data) => {
  const config = {}
  if (method === 'get') {
    config.params = data
  } else {
    config.data = data
  }
  return instance({
    url,
    method,
    ...config
  })
}

export const createFormAPI = (url, method, data) => {
  const config = {}
  config.data = data
  config.headers = {
    'Cache-Control': 'no-cache',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  config.responseType = 'json'
  config.transformRequest = [
    function (data) {
      let ret = ''
      for (const it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }
  ]
  return instance({
    url,
    method,
    ...config
  })
}
